<template>
  <div v-loading="pageLoading" class="taskHandle">
    <ContentWrap style="padding:0">
      <el-row :gutter="24">
        <el-col :span="8">
          <div class="taskHandle-content">
            <div v-if="$route.query.taskType==='2'">
              <p>
                订单编号:
                <font class="table-click-text" @click="orderDetail">{{ taskData.orderCode }}</font>
              </p>
              <p>回访对象：{{ taskData.callBackObject==='0'?'顾客':'收货人' }}</p>
              <p>被回访人：{{ taskData.customerName }}</p>
              <p>收货人电话：{{ taskData.customerPhone }}</p>
              <p>备用收货电话：</p>
              <p>任务名称：{{ taskData.taskName }}</p>
            </div>
            <div v-else-if="$route.query.taskType==='1'">
              <p>
                订单编号:
                <!-- <font style="color:#11A265">{{ taskData.orderCode }}</font> -->
                <font class="table-click-text" @click="orderDetail">{{ taskData.orderCode }}</font>
              </p>
              <p>回访对象：{{ taskData.customerName }}</p>
              <p>联系电话：{{ taskData.customerPhone }}<Button v-if="isVirtualPhone" type="primary" style="margin-left: 5px" @click="handlerClick">重新获取虚拟号</Button></p>
              <p>备用电话：</p>
              <p>任务名称：{{ taskData.taskName }}</p>
            </div>
            <div v-else>
              <p>
                <span>回访对象：{{ taskData.customerName }}</span>
                <span style="margin-left:20px">联系电话：{{ taskData.customerPhone }}</span>
              </p>
              <p class="remarks">备注信息1：{{ taskData.remarks1 }}</p>
              <p class="remarks">备注信息2：{{ taskData.remarks2 }}</p>
              <p class="remarks">备注信息3：{{ taskData.remarks3 }}</p>
              <p class="remarks">备注信息4：{{ taskData.remarks4 }}</p>
              <p class="remarks">备注信息5：{{ taskData.remarks5 }}</p>
              <p>任务名称：{{ taskData.taskName }}</p>
            </div>
            <FormContainer :column="1">
              <el-form
                ref="form"
                :model="formData"
                :rules="formRules"
                label-width="80px"
                label-position="left"
              >
                <el-form-item label="被回访电话：">
                  <div class="flex-box">
                    <el-input
                      v-model="formData.customerPhone"
                      class="flex"
                      :disabled="type!=='1'"
                      placeholder="请输入被回访电话"
                      style="max-width:220px"
                      clearable
                    />
                    <!-- <SvgIcon v-if="!disabledSubmit" icon-class="#dianhuaboda-solid" class-name="call-icon" @click="callPhone(formData.customerPhone)"></SvgIcon> -->
                    <Button v-if="!disabledSubmit" type="primary" @click="callPhone(formData.customerPhone)">外呼</Button>
                    <SecondDial v-if="!disabledSubmit" :record-id="recordId" style="margin-left:5px"></SecondDial>
                    <svg-icon icon-class="shouji-solid" style="cursor:pointer;color:#00926d;width:5em;height:2em;flex: 0 0 5em;margin-left: -1.5em;" @click="contactTpSms(formData.customerPhone)"></svg-icon>
                  </div>
                </el-form-item>
                <el-form-item prop="state" label="执行状态：">
                  <el-select v-model="formData.state" style="max-width:220px" :disabled="type!=='1'" clearable filterable>
                    <el-option
                      v-for="(option,index) in options"
                      :key="index"
                      :label="option.dictName"
                      :value="option.dictCode"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="callBackRemark" label="回访备注：">
                  <div class="flex-box">
                    <el-input
                      v-model.trim="formData.callBackRemark"
                      class="flex"
                      :disabled="type!=='1'"
                      type="textarea"
                      rows="6"
                      style="max-width:220px"
                      clearable
                    />
                    <Button type="primary" @click="toCreateOrder">创建工单</Button>
                  </div>
                </el-form-item>
              </el-form>
            </FormContainer>

            <div v-if="type!==0" class="button-container">
              <i style="flex-grow:1"></i>
              <Button ref="prev" type="primary" :loading="prevLoading" @click="prevTask">上一任务</Button>
              <Button v-if="!disabledSubmit" type="primary" @click="submit">提交</Button>
              <Button ref="next" type="primary" :loading="nextLoading" @click="nextTask">下一任务</Button>
              <i style="flex-grow:1"></i>
            </div>
            <Title title="关联工单" :title-class="$style.title" style="flex-wrap: wrap;">
              <table-box :data="workOrderData" :table-config="tableConfig"></table-box>
            </Title>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="taskHandle-content">
            <div class="border-warp">
              <el-scrollbar style="height:calc(100vh - 180px)" wrap-class="scrollbar-wrapper">
                <div class="questionnaire-content">

                  <div class="content-text">
                    <h1>问卷内容</h1>
                    <p>开头语：{{ questionnaire.startWords }}</p>
                    <div v-for="(chaper,index) in questionnaire.questionnaireChapterDTOList" :key="index">
                      <p
                        style="font-size:1.2rem;margin:0;font-weight:600"
                      >{{ chaper.chapter_index_text+'、'+ chaper.chapterTitle }}</p>
                      <Item
                        v-for="(item,index1) in chaper.questionnaireQuestionDTOList"
                        :key="index1"
                        :item="item"
                        :answer="answer"
                        :list="chaper.questionnaireQuestionDTOList"
                        :type="(taskData.callBackTaskResultDTOList.length||taskData.state === 6)?'1':'2'"
                        @change="(data)=>{answer=data}"
                      ></Item>
                    </div>
                    <p>结束语：{{ questionnaire.endWords }}</p>
                  </div>
                  <div v-if="!disabledSubmit" class="button-container">
                    <div class="next-button">
                      <Button type="primary" @click="submitQstnr">提交</Button>
                    </div>
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </el-col>
      </el-row>
    </ContentWrap>
    <CallOut ref="callOut"></CallOut>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import Item from '@/views/questionnaire/components/Item'
import SecondDial from '@/views/callBarPage/callOut/components/SecondDial'
import { ccDict } from '@/api/dataDict'
import { questionnaireDataSet } from '@/utils/questionnaire'
import Title from '@/components/Title'
import { workOrderRecordSimple } from '@/api/callBackTask'
import {
  callBackTaskOnlineDetail,
  callBackTaskOfflineDetail,
  callBackTaskImportDetail,
  callBackTaskCommit,
  commitQuestionnaire,
  getVirtualPhone
} from '@/api/callBackTask'
export default {
  name: 'TaskHandle',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    Item,
    SecondDial,
    Title
  },
  data() {
    return {
      pageLoading: false,
      prevLoading: false,
      nextLoading: false,
      formRules: {
        state: {
          required: true,
          message: '请选择执行状态',
          trigger: 'change'
        }
        // callBackRemark: {
        //   required: true,
        //   message: '请填写回访备注',
        //   trigger: 'change'
        // }
      },
      formData: {
        callBackRemark: '',
        customerPhone: '',
        id: '',
        objectMethod: '',
        state: ''
      },
      questionnaire: {},
      answer: {},
      type: 0, // 1为编辑，0为查看
      options: [],
      taskData: {
        tel: '',
        state: '',
        visitRemarks: ''
      },
      taskType: 0,
      // 排除的状态
      excludeState: [1, 2, '1', '2'],
      // 不能提交的状态
      disabledState: [4, 6, '4', '6'],
      // 是否已外呼
      callOuted: false,
      // 问卷是否提交
      questionnaireSubmited: false,
      // 当前任务id列表
      taskIdList: [],
      // 当前任务id
      currentId: null,
      // 通话记录id
      recordId: null,
      // 关联工单
      workOrderData: [],
      tableConfig: {
        hideFuncBar: true,
        setting: [
          {
            prop: 'workOrderCode',
            label: '工单编号',
            minWidth: 150,
            render: (h, row) => {
              return h('span', {
                class: 'table-handelclick-text',
                on: {
                  click: e => { e.preventDefault(); e.stopPropagation(); this.$router.push({ name: 'QueryOrderDetails', query: { id: row.id }}) }
                }
              }, row.workOrderCode)
            }
          },
          {
            prop: 'businessType1Name',
            label: '一级业务类型',
            minWidth: 130
          },
          {
            prop: 'businessType2Name',
            label: '二级业务类型',
            minWidth: 130
          },
          {
            prop: 'workOrderState',
            label: '工单状态',
            minWidth: 120,
            propEnum: {
              appCode: 'call-center',
              domainCode: 'marketing',
              dictTypeCode: 'WORK_ORDER_STATUS'
            }
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: 140
          }
        ]
      }
    }
  },
  computed: {
    disabledSubmit() {
      return this.disabledState.includes((this.taskData || {}).state)
    },
    // 是否是虚拟号
    isVirtualPhone() {
      return this.$route.query.taskType === '1' // && ((this.taskData.customerPhone || '').includes('-') || (this.formData.customerPhone || '').includes('-'))
    }
  },
  created() {
    var query = this.$route.query
    this.taskType = query.taskType
    if (query.type) {
      this.type = query.type
    }
    // 查看详情
    if (query.id) {
      this.currentId = query.id
    }
    // 获取任务列表
    if (query.key) {
      let tasks = sessionStorage.getItem(query.key)
      if (!tasks) return
      tasks = JSON.parse(tasks)
      this.currentId = tasks.currentId
      this.taskIdList = tasks.list
    }
    this.getTaskData()
    ccDict('STATE').then(res => {
      this.options = res.data.filter(e => {
        return !this.excludeState.includes(e.dictCode)
      }).map(e => {
        e.dictCode = this.$strToNumber(e.dictCode)
        return e
      })
    })
  },
  beforeDestroy() {
    // 删除当前缓存的任务列表
  },
  methods: {
    // 执行状态是成功时，是否可以提交留言信息
    submitableCallOut() {
      if (!this.callOuted) {
        this.$message.error('没有外呼！')
        return false
      }
      if (this.formData.state === 6 || this.formData.state === '6') {
        if (!this.questionnaireSubmited) {
          this.$message.error('请先提交问卷！')
          return false
        }
      }
      return true
    },
    // 重置提交外呼状态
    resetSubmitState() {
      this.questionnaireSubmited = false
      this.callOuted = false
      this.recordId = null
    },
    // 检查详情状态
    checkState(state) {
      return this.excludeState.includes(state) ? '' : state
    },
    // 导入详情
    exportDetail() {
      return callBackTaskImportDetail(this.currentId)
        .then(res => {
          if (res.success === 1) {
            // 处理结果
            return {
              res,
              objectMethod: 0
            }
          }
        })
    },
    // 线下详情
    offlineDetail() {
      return callBackTaskOfflineDetail(this.currentId)
        .then(res => {
          if (res.success === 1) {
            // 处理结果
            return {
              res,
              objectMethod: 2
            }
          }
        })
    },
    // 线上详情
    onlineDetail() {
      return callBackTaskOnlineDetail(this.currentId)
        .then(res => {
          if (res.success === 1) {
            return {
              res,
              objectMethod: 1
            }
          }
        })
    },
    // 获取详情
    getDetail() {
      // 导入
      if (this.taskType === '0') {
        return this.exportDetail()
      } else if (this.taskType === '2') {
        // 线下
        return this.offlineDetail()
      } else if (this.taskType === '1') {
        // 线上
        return this.onlineDetail()
      }
    },
    // 获取详情后重置状态
    getTaskData() {
      this.nextLoading = true
      this.prevLoading = true
      this.pageLoading = true
      this.getDetail().then(result => {
        const res = result.res || {}
        const objectMethod = result.objectMethod
        // 处理数据
        this.taskData = res.data
        this.formData = {
          callBackRemark: res.data.callBackRemark,
          customerPhone: res.data.customerPhone,
          id: res.data.id,
          objectMethod,
          state: this.checkState(res.data.state)
        }
        // 关联工单
        this.getWorkOrderCode()
        this.questionnaireSet(res.data.questionnaireDetailDTO, res.data.callBackTaskResultDTOList)

        this.resetSubmitState()
        this.$refs.form.clearValidate()
        // 更新sessionStorage
        if (this.$route.query.key) {
          sessionStorage.setItem(this.$route.query.key, JSON.stringify({
            currentId: this.currentId,
            list: this.taskIdList
          }))
        }
        return res
      }).finally(() => {
        this.nextLoading = false
        this.prevLoading = false
        this.pageLoading = false
      })
    },
    // 点击拨打按钮
    callPhone(phone) {
      if (!phone) {
        this.$message.warning('无效电话号码！')
        return
      }
      // 处理虚拟号
      if (phone.includes('-')) {
        const t = phone.split('-')
        if (t.length === 2) {
          phone = t.shift()
        } else if (t.length > 2) {
          t.pop()
          phone = t.join('-')
        }
      }
      this.$msgbox({
        type: 'warning',
        title: '外呼',
        message: '确认外呼？',
        showCancelButton: true
      }).then(() => {
        // 需要记录到通话记录的数据
        const callOptions = {
          businessType: 3, // 业务任务类型1：工单 2：关怀 3：回访 4:crm
          businessCode: this.taskData.taskId,
          callType: 4,
          customerName: this.taskData.customerName
        }
        this.$refs.callOut.debounceCallOut(phone, { callOptions }).then(recordId => {
          console.log('通话记录id: ', recordId)
          this.recordId = recordId
        }).finally(() => {
          this.callOuted = true // 是否外呼
        })
      }).catch(e => {})
    },
    // 上一任务
    prevTask() {
      const list = this.taskIdList
      const i = list.indexOf(this.formData.id)
      if (i > 0) {
        this.currentId = list[i - 1]
        this.getTaskData()
      } else {
        this.$message.error('当前任务为第一项任务!')
      }
    },
    // 提交
    submit() {
      if (!this.submitableCallOut()) {
        return
      }
      return this.$refs.form.validate().then(() => {
        return callBackTaskCommit(this.formData)
          .then(res => {
            this.$message({
              message: '提交成功!',
              type: 'success'
            })
          })
          .catch(er => {})
      }).finally(() => {
        this.recordId = null
      })
    },
    // 下一任务
    nextTask() {
      const list = this.taskIdList
      const i = list.indexOf(this.formData.id)
      if (i < list.length - 1) {
        this.currentId = list[i + 1]
        this.getTaskData()
      } else {
        this.$message.error('当前任务为最后一项任务!请返回列表重新查询')
      }
    },
    // 问卷提交
    submitQstnr() {
      const subList = []
      for (const chaper of this.questionnaire.questionnaireChapterDTOList || []) {
        const list = chaper.questionnaireQuestionDTOList || []
        for (const i in list) {
          if (list[i].questionType !== 3) {
            const item = {
              taskObjectId: this.formData.id,
              questionTitle: list[i].questionTitle,
              questionId: list[i].id,
              optionDTOList: []
            }
            const optionSelList = []
            list[i].questionOptionDTOList.forEach(e => {
              if (list[i].questionType === 2) {
                if (this.answer[list[i].id][e.id].enterContent) {
                  optionSelList.push({
                    optionId: e.id,
                    optionContent: e.optionContent,
                    inputContent: this.answer[list[i].id][e.id].enterContent,
                    dr: 0
                  })
                }
              } else {
                if (this.answer[list[i].id][e.id].isSel) {
                  optionSelList.push({
                    optionId: e.id,
                    optionContent: e.optionContent,
                    inputContent: this.answer[list[i].id][e.id].enterContent,
                    dr: 0
                  })
                }
              }
            })
            item.optionDTOList = optionSelList
            subList.push(item)
          }
        }
      }
      return commitQuestionnaire(subList).then(res => {
        this.$message({
          message: '提交成功!',
          type: 'success'
        })
        this.questionnaireSubmited = true
      }).catch(er => {})
    },
    // 问卷内容处理
    questionnaireSet(data, list) {
      const obj = questionnaireDataSet(data, data.questionnaireChapterDTOList)
      if (this.taskData.state !== 6) {
        this.answer = obj.answer
      } else {
        list.forEach(e => {
          e.optionDTOList.forEach(option => {
            if (obj.answer[e.questionId]) {
              obj.answer[e.questionId][option.optionId].isSel = true
              obj.answer[e.questionId][option.optionId].enterContent = option.inputContent
            }
          })
        })
        this.answer = obj.answer
      }
      this.questionnaire = obj.questionnaire
      this.$forceUpdate()
    },
    orderDetail() {
      if (this.taskType === '2') {
        // 线下
        const { orderCode, source, disCode } = this.taskData
        if (source === 'top1') {
          this.$router.push({ name: 'ShopRetailDetail', query: { saleOrderCode: orderCode, disCode }})
        } else {
          this.$router.push({ name: 'Top2RetailDetail', query: { retailOrderCode: orderCode, disCode }})
        }
      } else {
        // 线上
        // this.$router.push({ name: 'GoodsDetail', query: { pcode: this.taskData.orderCode }})
        this.$router.push({
          path: `/myiframe/urlPath?src=%2Fec-order-service%2ForderQuery&name=ECO订单查询&menuCode=${/^ccdev/.test(location.host) ? 'PC3539753' : 'PC7287737'}&dcCode=${this.taskData.orderCode}`
        })
      }
    },
    toCreateOrder() {
      const query = { taskType: this.taskType }
      Object.entries(this.taskData).forEach(([k, v]) => {
        if (typeof v !== 'object') {
          query[k] = v
        }
      })
      this.$router.push({
        name: 'CreateOrder',
        query: {
          taskData: window.encodeURIComponent(JSON.stringify(query)),
          recordId: this.recordId,
          visitForm: window.encodeURIComponent(JSON.stringify(this.formData))
        }
      })
    },
    // 重新获取虚拟号
    handlerClick() {
      return getVirtualPhone(this.currentId).then(res => {
        const data = res.data
        if (!data.virtualTel) {
          this.$message.warning('虚拟号更新失败!')
          return
        }
        // 设置虚拟号
        // const phone = `${data.virtualPhone}-${res.virPhone}`
        this.$set(this.formData, 'customerPhone', data.virtualTel)
        this.$set(this.taskData, 'customerPhone', data.virtualTel)
        this.$message.success('虚拟号更新成功!')
      })
    },
    // 客户联系电话  发送短信
    contactTpSms(phone) {
      if (phone === '' || phone === undefined) {
        this.$message.warning(`请输入手机号码!`)
        return
      }
      if (!/^1\d{10}/.test(phone)) {
        this.$message.warning(`【${phone}】不是手机号码!`)
        return
      }
      const callTel = phone.trim()
      this.$router.push({ name: 'SMSSend', query: { callTel }})
    },
    // 获取关联工单
    getWorkOrderCode(detail) {
      const data = new FormData()
      data.append('pageFlag', false)
      data.append('page', 1)
      let filtersRaw = []
      if (this.$route.query.taskType === '1') {
        filtersRaw = [
          { id: 'orderCode', property: 'orderCode', value: this.taskData.orderCode, operator: '=' },
          { id: 'contactPhone', property: 'contactPhone', value: this.taskData.customerPhone, operator: '=' },
          { id: 'nickname', property: 'nickname', value: this.taskData.buyer, operator: '=' }
        ]
      } else {
        filtersRaw = [
          { id: 'contactPhone', property: 'contactPhone', value: this.taskData.customerPhone, operator: '=' }
        ]
      }

      data.append('filtersRaw', JSON.stringify(filtersRaw))
      return workOrderRecordSimple(data).then(res => {
        this.workOrderData = res.data.records
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.taskHandle-content {
  padding: 20px 20px;
  &>div{
    &>p:first-child{
      margin-top: 0;
    }
  }
  .remarks {
    margin: 10px 0;
  }
  .questionnaire-content {
    padding: 0 20px 20px;
    .content-text {
      min-height: 400px;
    }
    h1 {
      text-align: center;
    }
  }
  .table-handelclick-text {
    color: #3DC094;
    cursor: pointer;
  }
}
.border-warp{
  border: 1px solid #999;
  border-radius: 4px;
}
.flex-box{
  display: flex;
  align-items: flex-start;
  &>.flex{
    flex: 0 1 auto;
  }
  &>button{
    flex: 0 0 auto;
  }
  &>button:first-of-type{
    margin-left: 10px;
  }
}
</style>
<style lang="scss" module>
.title{
  font-size: 16px !important;
  font-weight: 700 !important;
}
</style>
